package phase01.module4.code.question4;

import java.io.*;
import java.net.Socket;

public class ServiceThread extends Thread {
    private final Socket s;

    public ServiceThread(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        try(BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            PrintStream ps = new PrintStream(s.getOutputStream());
            ObjectInputStream oi = new ObjectInputStream(s.getInputStream());
            ObjectOutputStream oo = new ObjectOutputStream(s.getOutputStream())
        ) {
            while (true) {
                String msg = br.readLine();
                if ("bye".equalsIgnoreCase(msg)) {
                    System.out.println("结束服务！");
                    System.out.println("==============================================================================================");
                    break;
                }
                ps.println("连接服务器成功！");
                UserMessage umReq = (UserMessage) oi.readObject();
                System.out.println("收到登录请求：" + umReq);
                User user = umReq.getUser();
                String username = user.getUsername();
                String password = user.getPassword();
                if ("admin".equals(username) && "123456".equals(password)) {
                    umReq.setMessageType("success");
                } else {
                    umReq.setMessageType("fail");
                }
                oo.writeObject(umReq);
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
